{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "# Scaling up ML using Cloud AI Platform\n",
    "\n",
    "In this notebook, we take a previously developed TensorFlow model to predict taxifare rides and package it up so that it can be run in Cloud AI Platform. For now, we'll run this on a small dataset. The model that was developed is rather simplistic, and therefore, the accuracy of the model is not great either.  However, this notebook illustrates *how* to package up a TensorFlow model to run it within Cloud AI Platform. \n",
    "\n",
    "Later in the course, we will look at ways to make a more effective machine learning model."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "## Environment variables for project and bucket\n",
    "\n",
    "Note that:\n",
    "<ol>\n",
    "<li> Your project id is the *unique* string that identifies your project (not the project name). You can find this from the GCP Console dashboard's Home page.  My dashboard reads:  <b>Project ID:</b> cloud-training-demos </li>\n",
    "<li> Cloud training often involves saving and restoring model files. If you don't have a bucket already, I suggest that you create one from the GCP console (because it will dynamically check whether the bucket name you want is available). A common pattern is to prefix the bucket name by the project id, so that it is unique. Also, for cost reasons, you might want to use a single region bucket. </li>\n",
    "</ol>\n",
    "<b>Change the cell below</b> to reflect your Project ID and bucket name.\n"
   ]
  },
  {
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
 "!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "import os\n",
    "PROJECT = 'cloud-training-demos' # REPLACE WITH YOUR PROJECT ID\n",
    "BUCKET = 'cloud-training-demos-ml' # REPLACE WITH YOUR BUCKET NAME\n",
    "REGION = 'us-central1' # REPLACE WITH YOUR BUCKET REGION e.g. us-central1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# For Python Code\n",
    "# Model Info\n",
    "MODEL_NAME = 'taxifare'\n",
    "# Model Version\n",
    "MODEL_VERSION = 'v1'\n",
    "# Training Directory name\n",
    "TRAINING_DIR = 'taxi_trained'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "# for bash\n",
    "os.environ['PROJECT'] = PROJECT\n",
    "os.environ['BUCKET'] = BUCKET\n",
    "os.environ['REGION'] = REGION\n",
    "os.environ['MODEL_NAME'] = MODEL_NAME\n",
    "os.environ['MODEL_VERSION'] = MODEL_VERSION\n",
    "os.environ['TRAINING_DIR'] = TRAINING_DIR \n",
    "os.environ['TFVERSION'] = '2.5'  # Tensorflow version"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "%%bash\n",
    "gcloud config set project $PROJECT\n",
    "gcloud config set compute/region $REGION"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "## Packaging up the code\n",
    "\n",
    "Take your code and put into a standard Python package structure.  <a href=\"taxifare/trainer/model.py\">model.py</a> and <a href=\"taxifare/trainer/task.py\">task.py</a> containing the Tensorflow code from earlier (explore the <a href=\"taxifare/trainer/\">directory structure</a>)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "find ${MODEL_NAME}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "cat ${MODEL_NAME}/trainer/model.py"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "## Find absolute paths to your data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "Note the absolute paths below. /content is mapped in Datalab to where the home icon takes you"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "echo \"Working Directory: ${PWD}\"\n",
    "echo \"Head of taxi-train.csv\"\n",
    "head -1 $PWD/taxi-train.csv\n",
    "echo \"Head of taxi-valid.csv\"\n",
    "head -1 $PWD/taxi-valid.csv"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "## Running the Python module from the command-line"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Clean model training dir/output dir"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "# This is so that the trained model is started fresh each time. However, this needs to be done before \n",
    "rm -rf $PWD/${TRAINING_DIR}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "# Setup python so it sees the task module which controls the model.py\n",
    "export PYTHONPATH=${PYTHONPATH}:${PWD}/${MODEL_NAME}\n",
    "# Currently set for python 2.  To run with python 3 \n",
    "#    1.  Replace 'python' with 'python3' in the following command\n",
    "#    2.  Edit trainer/task.py to reflect proper module import method \n",
    "python -m trainer.task \\\n",
    "   --train_data_paths=\"${PWD}/taxi-train*\" \\\n",
    "   --eval_data_paths=${PWD}/taxi-valid.csv  \\\n",
    "   --output_dir=${PWD}/${TRAINING_DIR} \\\n",
    "   --train_steps=1000 --job-dir=./tmp"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "%%bash\n",
    "ls $PWD/${TRAINING_DIR}/export/exporter/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "%%writefile ./test.json\n",
    "{\"pickuplon\": -73.885262,\"pickuplat\": 40.773008,\"dropofflon\": -73.987232,\"dropofflat\": 40.732403,\"passengers\": 2}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "%%bash\n",
    "sudo find \"/usr/lib/google-cloud-sdk/lib/googlecloudsdk/command_lib/ml_engine\" -name '*.pyc' -delete"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "%%bash\n",
    "# This model dir is the model exported after training and is used for prediction\n",
    "#\n",
    "model_dir=$(ls ${PWD}/${TRAINING_DIR}/export/exporter | tail -1)\n",
    "# predict using the trained model\n",
    "gcloud ai-platform local predict  \\\n",
    "    --model-dir=${PWD}/${TRAINING_DIR}/export/exporter/${model_dir} \\\n",
    "    --json-instances=./test.json"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Clean model training dir/output dir"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "# This is so that the trained model is started fresh each time. However, this needs to be done before \n",
    "rm -rf $PWD/${TRAINING_DIR}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "## Running locally using gcloud"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "%%bash\n",
    "# Use Cloud Machine Learning Engine to train the model in local file system\n",
    "gcloud ai-platform local train \\\n",
    "   --module-name=trainer.task \\\n",
    "   --package-path=${PWD}/${MODEL_NAME}/trainer \\\n",
    "   -- \\\n",
    "   --train_data_paths=${PWD}/taxi-train.csv \\\n",
    "   --eval_data_paths=${PWD}/taxi-valid.csv  \\\n",
    "   --train_steps=1000 \\\n",
    "   --output_dir=${PWD}/${TRAINING_DIR} "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "ls $PWD/${TRAINING_DIR}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Submit training job using gcloud\n",
    "\n",
    "First copy the training data to the cloud.  Then, launch a training job.\n",
    "\n",
    "After you submit the job, go to the cloud console (http://console.cloud.google.com) and select <b>AI Platform | Jobs</b> to monitor progress.  \n",
    "\n",
    "<b>Note:</b> Don't be concerned if the notebook stalls (with a blue progress bar) or returns with an error about being unable to refresh auth tokens. This is a long-lived Cloud job and work is going on in the cloud.  Use the Cloud Console link (above) to monitor the job."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "%%bash\n",
    "# Clear Cloud Storage bucket and copy the CSV files to Cloud Storage bucket\n",
    "echo $BUCKET\n",
    "gcloud storage rm --recursive --continue-on-error gs://${BUCKET}/${MODEL_NAME}/smallinput/\n",
    "gcloud storage cp ${PWD}/*.csv gs://${BUCKET}/${MODEL_NAME}/smallinput/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "%%bash\n",
    "OUTDIR=gs://${BUCKET}/${MODEL_NAME}/smallinput/${TRAINING_DIR}\n",
    "JOBNAME=${MODEL_NAME}_$(date -u +%y%m%d_%H%M%S)\n",
    "echo $OUTDIR $REGION $JOBNAME\n",
    "# Clear the Cloud Storage Bucket used for the training job\n",
    "gcloud storage rm --recursive --continue-on-error $OUTDIR\n",
    "gcloud ai-platform jobs submit training $JOBNAME \\\n",
    "   --region=$REGION \\\n",
    "   --module-name=trainer.task \\\n",
    "   --package-path=${PWD}/${MODEL_NAME}/trainer \\\n",
    "   --job-dir=$OUTDIR \\\n",
    "   --staging-bucket=gs://$BUCKET \\\n",
    "   --scale-tier=BASIC \\\n",
    "   --runtime-version 2.3 \\\n",
    "   --python-version 3.5 \\\n",
    "   -- \\\n",
    "   --train_data_paths=\"gs://${BUCKET}/${MODEL_NAME}/smallinput/taxi-train*\" \\\n",
    "   --eval_data_paths=\"gs://${BUCKET}/${MODEL_NAME}/smallinput/taxi-valid*\"  \\\n",
    "   --output_dir=$OUTDIR \\\n",
    "   --train_steps=10000"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "Don't be concerned if the notebook appears stalled (with a blue progress bar) or returns with an error about being unable to refresh auth tokens. This is a long-lived Cloud job and work is going on in the cloud. \n",
    "\n",
    "<b>Use the Cloud Console link to monitor the job and do NOT proceed until the job is done.</b>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "%%bash\n",
    "gcloud storage ls gs://${BUCKET}/${MODEL_NAME}/smallinput"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "## Train on larger dataset\n",
    "\n",
    "I have already followed the steps below and the files are already available. <b> You don't need to do the steps in this comment. </b> In the next chapter (on feature engineering), we will avoid all this manual processing by using Cloud Dataflow.\n",
    "\n",
    "Go to http://bigquery.cloud.google.com/ and type the query:\n",
    "<pre>\n",
    "SELECT\n",
    "  (tolls_amount + fare_amount) AS fare_amount,\n",
    "  pickup_longitude AS pickuplon,\n",
    "  pickup_latitude AS pickuplat,\n",
    "  dropoff_longitude AS dropofflon,\n",
    "  dropoff_latitude AS dropofflat,\n",
    "  passenger_count*1.0 AS passengers,\n",
    "  'nokeyindata' AS key\n",
    "FROM\n",
    "  [nyc-tlc:yellow.trips]\n",
    "WHERE\n",
    "  trip_distance > 0\n",
    "  AND fare_amount >= 2.5\n",
    "  AND pickup_longitude > -78\n",
    "  AND pickup_longitude < -70\n",
    "  AND dropoff_longitude > -78\n",
    "  AND dropoff_longitude < -70\n",
    "  AND pickup_latitude > 37\n",
    "  AND pickup_latitude < 45\n",
    "  AND dropoff_latitude > 37\n",
    "  AND dropoff_latitude < 45\n",
    "  AND passenger_count > 0\n",
    "  AND ABS(HASH(pickup_datetime)) % 1000 == 1\n",
    "</pre>\n",
    "\n",
    "Note that this is now 1,000,000 rows (i.e. 100x the original dataset).  Export this to CSV using the following steps (Note that <b>I have already done this and made the resulting GCS data publicly available</b>, so you don't need to do it.):\n",
    "<ol>\n",
    "<li> Click on the \"Save As Table\" button and note down the name of the dataset and table.\n",
    "<li> On the BigQuery console, find the newly exported table in the left-hand-side menu, and click on the name.\n",
    "<li> Click on \"Export Table\"\n",
    "<li> Supply your bucket name and give it the name train.csv (for example: gs://cloud-training-demos-ml/taxifare/ch3/train.csv). Note down what this is.  Wait for the job to finish (look at the \"Job History\" on the left-hand-side menu)\n",
    "<li> In the query above, change the final \"== 1\" to \"== 2\" and export this to Cloud Storage as valid.csv (e.g.  gs://cloud-training-demos-ml/taxifare/ch3/valid.csv)\n",
    "<li> Download the two files, remove the header line and upload it back to GCS.\n",
    "</ol>\n",
    "\n",
    "<p/>\n",
    "<p/>\n",
    "\n",
    "<h2> Run Cloud training on 1-million row dataset </h2>\n",
    "\n",
    "This took 60 minutes and uses as input 1-million rows.  The model is exactly the same as above. The only changes are to the input (to use the larger dataset) and to the Cloud MLE tier (to use STANDARD_1 instead of BASIC -- STANDARD_1 is approximately 10x more powerful than BASIC).  At the end of the training the loss was 32, but the RMSE (calculated on the validation dataset) was stubbornly at 9.03. So, simply adding more data doesn't help."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "%%bash\n",
    "\n",
    "OUTDIR=gs://${BUCKET}/${MODEL_NAME}/${TRAINING_DIR}\n",
    "JOBNAME=${MODEL_NAME}_$(date -u +%y%m%d_%H%M%S)\n",
    "CRS_BUCKET=cloud-training-demos # use the already exported data\n",
    "echo $OUTDIR $REGION $JOBNAME\n",
    "gcloud storage rm --recursive --continue-on-error $OUTDIR\n",
    "gcloud ai-platform jobs submit training $JOBNAME \\\n",
    "   --region=$REGION \\\n",
    "   --module-name=trainer.task \\\n",
    "   --package-path=${PWD}/${MODEL_NAME}/trainer \\\n",
    "   --job-dir=$OUTDIR \\\n",
    "   --staging-bucket=gs://$BUCKET \\\n",
    "   --scale-tier=STANDARD_1 \\\n",
    "   --runtime-version 2.3 \\\n",
    "   --python-version 3.5 \\\n",
    "   -- \\\n",
    "   --train_data_paths=\"gs://${CRS_BUCKET}/${MODEL_NAME}/ch3/train.csv\" \\\n",
    "   --eval_data_paths=\"gs://${CRS_BUCKET}/${MODEL_NAME}/ch3/valid.csv\"  \\\n",
    "   --output_dir=$OUTDIR \\\n",
    "   --train_steps=100000"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "## Challenge Exercise\n",
    "\n",
    "Modify your solution to the challenge exercise in d_trainandevaluate.ipynb appropriately. Make sure that you implement training and deployment. Increase the size of your dataset by 10x since you are running on the cloud. Does your accuracy improve?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "Copyright 2021 Google Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
